import axios from "axios";

interface RequestConfig {
  baseUrl: string;
  data?: any;
}

enum RequestMethod {
  GET = "GET",
  POST = "POST",
  PUT = "PUT",
}

// 根据环境变量来获取baseURL
export const baseUrl = 'http://101.132.89.143:8001';

const requestConfig: RequestConfig = {
  baseUrl
};

class Request {
  private baseConfig: RequestConfig;

  constructor(config: RequestConfig) {
    this.baseConfig = config;
  }

  private async fire<T>(url: string, method: RequestMethod, data?: any): Promise<T> {
    const fullUrl = `${this.baseConfig.baseUrl}${url}`;
    try {
      const response = await axios.request<T>({
        url: fullUrl,
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        data, // axios 会自动处理数据的 JSON 编码
      });
      return response.data;
    } catch (error) {
      console.error("Request failed:", error.response?.data || error.message);
      throw error;
    }
  }

  public async post<T>(url: string, data?: any) {
    try {
      return await this.fire<T>(url, RequestMethod.POST, data);
    } catch (error) {
      return {} as T;
    }
  }

  public async get<T>(url: string) {
    try {
      return await this.fire<T>(url, RequestMethod.GET);
    } catch (error) {
      return {} as T;
    }
  }
}

export const request = new Request(requestConfig);
